package com.anti.modular.bus.roomreservation.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.anti.core.context.login.LoginContextHolder;
import com.anti.core.utils.IdFlowingUtil;
import com.anti.jdbc.DBUtils;
import com.anti.jdbc.support.page.PageParam;
import com.anti.jdbc.support.page.PageResult;
import com.anti.commom.core.exception.BusinessException;
import com.anti.modular.bus.basicinformation.entity.BasicInformation;
import com.anti.modular.bus.billwater.entity.BillWater;
import com.anti.modular.bus.billwater.entity.BillWaterRoom;
import com.anti.modular.bus.billwater.param.BillWaterParam;
import com.anti.modular.bus.billwater.service.BillWaterService;
import com.anti.modular.bus.billwaterdetail.entity.BillWaterDetail;
import com.anti.modular.bus.billwaterdetail.service.BillWaterDetailService;
import com.anti.modular.bus.busmeansoftransaction.entity.BusMeansOfTransaction;
import com.anti.modular.bus.busmeansoftransaction.param.BusMeansOfTransactionParam;
import com.anti.modular.bus.busmeansoftransaction.service.BusMeansOfTransactionService;
import com.anti.modular.bus.busrealestatefloor.entity.BusRealEstateFloor;
import com.anti.modular.bus.busroom.param.BusRoomParam;
import com.anti.modular.bus.roomreservation.entity.RoomReservation;
import com.anti.modular.bus.roomreservation.enums.RoomReservationExceptionEnum;
import com.anti.modular.bus.roomreservation.param.RoomReservationParam;
import com.anti.modular.bus.roomreservation.service.RoomReservationService;
import com.anti.modular.sys.auth.pojo.SysLoginUser;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * 房间预定service接口实现类
 *
 * @author anti
 * @date 2021-04-23 09:43:48
 */
@Service
public class RoomReservationServiceImpl implements RoomReservationService {
    @Resource
    DBUtils dbUtils;
    @Resource
    BusMeansOfTransactionService busMeansOfTransactionService;
    @Resource
    BillWaterService billWaterService;
    @Resource
    BillWaterDetailService billWaterDetailService;

    @Override
    public RoomReservation getById(RoomReservationParam roomReservationParam){
        String sql="select * from room_reservation where id =? ";
        return dbUtils.get(sql,RoomReservation.class,roomReservationParam.getId());
    }

    @Override
    public RoomReservation getReservationById(Long id) {
        String sql="select * from room_reservation where id =? ";
        return dbUtils.get(sql,RoomReservation.class,id);
    }

    @Override
    public PageResult page(PageParam pageParam,RoomReservationParam roomReservationParam) {
        StringBuilder sb=new StringBuilder("select * from room_reservation where 1=1 ");
        ArrayList<Object> param = CollectionUtil.newArrayList();
        if (ObjectUtil.isNotNull(roomReservationParam)) {
            if (ObjectUtil.isNotEmpty(roomReservationParam.getType())){
                if ("1".equals(roomReservationParam.getType())){
                    sb.append(" and status = 0");
                }else {
                    sb.append(" and status <> 0 and  status <> 3");
                }
            }
            // 根据房间编号 查询
            if (ObjectUtil.isNotEmpty(roomReservationParam.getSearchValue())) {
               sb.append(" and ( room_code like ?  or reservation like ? )");
               param.add("%"+roomReservationParam.getSearchValue()+"%");
               param.add("%"+roomReservationParam.getSearchValue()+"%");
            }
        }
        PageResult pageResult = dbUtils.query(pageParam, sb.toString(),RoomReservation.class, param.toArray());
        return pageResult;
    }

    @Override
    public List<RoomReservation> list(RoomReservationParam roomReservationParam) {
        String sql="";
        return dbUtils.query(sql,RoomReservation.class);
    }

    @Override
    public void add(RoomReservationParam roomReservationParam) {
        checkParam(roomReservationParam,false);
        RoomReservation roomReservation = new RoomReservation();
        BeanUtil.copyProperties(roomReservationParam, roomReservation);
        BusMeansOfTransactionParam busMeansOfTransactionParam=new BusMeansOfTransactionParam();
        busMeansOfTransactionParam.setId(roomReservationParam.getCollectionType().longValue());
        BusMeansOfTransaction means = busMeansOfTransactionService.getById(busMeansOfTransactionParam);
        roomReservation.setCollectionTypeName(means.getName());
        roomReservation.setCreateTime(new Date());
        SysLoginUser sysLoginUser = LoginContextHolder.me().getSysLoginUser();
        roomReservation.setCreateUser(sysLoginUser.getId());
        roomReservation.setCreateUserName(sysLoginUser.getName());
        String zqName = getZqName(roomReservationParam);
        roomReservation.setReceiptCycle(zqName);
        String snowflakesId = IdFlowingUtil.getSnowflakesId("RMYD");
        roomReservation.setYdNo(snowflakesId);
        roomReservation.setStatus(0);
        String key = dbUtils.insertKey(roomReservation).toString();
        BillWater billWaterParam = getBillWaterParam(roomReservation, key);
        // 保存定金流水表
        Long billWaterKey = billWaterService.add(billWaterParam);
        //保存流水房間關聯表
        BillWaterRoom billWaterRoom=new BillWaterRoom();
        billWaterRoom.setBillWaterId(billWaterKey);
        billWaterRoom.setRoomId(roomReservation.getRoomId());
        billWaterRoom.setRoomName(roomReservation.getRoomCode());
        billWaterRoom.setName(roomReservation.getReservation());
        dbUtils.insert(billWaterRoom);
        //詳情
        BillWaterDetail billWaterDetail=new BillWaterDetail();
        billWaterDetail.setAmount(roomReservation.getDeposit());
        billWaterDetail.setBillWaterId(billWaterKey);
        billWaterDetail.setBillInOutType(1);
        billWaterDetail.setName("定金");
        billWaterDetail.setStatus(0);
        billWaterDetail.setCreateUser(LoginContextHolder.me().getSysLoginUserId());
        billWaterDetail.setCreateTime(new Date());
        // 保存定金流水詳情表
        billWaterDetailService.add(billWaterDetail);
    }

    private BillWater getBillWaterParam(RoomReservation roomReservation, String key) {
        BillWater billWaterParam =new BillWater();
        billWaterParam.setRoomName(roomReservation.getRoomCode());
        billWaterParam.setName(roomReservation.getReservation());
        billWaterParam.setSource(2);
        billWaterParam.setAmount(roomReservation.getDeposit());
        billWaterParam.setReceiveDate(roomReservation.getCollectionDate());
        billWaterParam.setShouldReceiveDate(roomReservation.getCollectionDate());
        Date date = new Date();
        billWaterParam.setOperatingDate(date);
        billWaterParam.setTransaction(roomReservation.getCollectionType());
        billWaterParam.setTransactionName(roomReservation.getCollectionTypeName());
        billWaterParam.setManagerId(roomReservation.getCreateUser());
        billWaterParam.setManager(roomReservation.getCreateUserName());
        billWaterParam.setManagertTime(roomReservation.getCreateTime());
        billWaterParam.setAuditFlag(0);
        billWaterParam.setNo(roomReservation.getYdNo());
        billWaterParam.setBillInOutType(1);
        billWaterParam.setBillId(Long.parseLong(key));
        billWaterParam.setBillTable("room_reservation");
        billWaterParam.setStatus(0);
        Long sysLoginUserId = LoginContextHolder.me().getSysLoginUserId();
        billWaterParam.setCreateUser(sysLoginUserId);
        billWaterParam.setCreateTime(date);
        return billWaterParam;
    }


    public void delete(RoomReservationParam roomReservationParam) {
        String sql="delete  from room_reservation where id =? ";
        dbUtils.execSql(sql,roomReservationParam.getId());
    }

    @Override
    public void deleteAllSelect(List<Long> roomReservationParam) {
        if (roomReservationParam.size()<=0){
            return;
        }
        String sql="update room_reservation set status = 3  where id in (:ids) ";
        HashMap<String, Object> hashMap = CollectionUtil.newHashMap();
        hashMap.put("ids",roomReservationParam);
        dbUtils.execSql(sql,hashMap);
        for (int i = 0; i < roomReservationParam.size(); i++) {
            Long aLong = roomReservationParam.get(i);
            billWaterService.deleteAllByType(aLong,"room_reservation");
        }
    }

    public void edit(RoomReservationParam roomReservationParam) {
        RoomReservation roomReservation = this.queryRoomReservation(roomReservationParam);
        BeanUtil.copyProperties(roomReservationParam, roomReservation);
        dbUtils.update(roomReservation);
    }

    @Override
    public void editQxyd(RoomReservationParam roomReservationParam) {
        String snowflakesId = IdFlowingUtil.getSnowflakesId("QXYD");
        RoomReservation roomReservation = this.queryRoomReservation(roomReservationParam);
        roomReservation.setRefundStyle(1);
        roomReservation.setStatus(2);
        roomReservation.setOperatingYdNo(snowflakesId);
        roomReservation.setOperatingTime(roomReservationParam.getOperatingTime());
        roomReservation.setOperatingUser(LoginContextHolder.me().getSysLoginUserId());
        roomReservation.setUpdateTime(new Date());
        roomReservation.setUpdateUser(LoginContextHolder.me().getSysLoginUserId());
        dbUtils.update(roomReservation);
    }

    @Override
    public RoomReservation detail(RoomReservationParam roomReservationParam) {
        return this.queryRoomReservation(roomReservationParam);
    }

    /**
     * 获取房间预定
     *
     * @author anti
     * @date 2021-04-23 09:43:48
     */
    private RoomReservation queryRoomReservation(RoomReservationParam roomReservationParam) {
        RoomReservation roomReservation = this.getById(roomReservationParam);
        if (ObjectUtil.isNull(roomReservation)) {
            throw new BusinessException(RoomReservationExceptionEnum.NOT_EXIST);
        }
        return roomReservation;
    }

    private void checkParam(RoomReservationParam roomReservationParam, boolean isExcludeSelf){
        Long id = roomReservationParam.getRoomId();

        //构建带name查询条件
        StringBuilder nameSb=new StringBuilder("select count(*) from room_reservation where status =0 and room_id =? ");

        //查询重复记录的数量
        int countByName = dbUtils.getIntValue(nameSb.toString(),id);

        //如果存在重复的记录，抛出异常，直接返回前端
        if (countByName >= 1) {
            throw new BusinessException(0,"該房間編號已經被預定，請重新選擇");
        }
    }
    public String getZqName(RoomReservationParam roomReservationParam){
        // 依据（字典 1日 2月 3年 4一次付清）
        int receiptyj = roomReservationParam.getReceiptYj();
        // 付 （字典 付1-付18）
        int receiptfu = roomReservationParam.getReceiptFu();
        // 押 （字典 押1-押18-自定义19）
        int receiptya = roomReservationParam.getReceiptYa();
        if (receiptyj == 4){
            return "一次付清";
        }
        String dw="月";
        if (receiptyj == 1){
            dw="日";
        }else if (receiptyj == 2){
            dw="月";
        }else if (receiptyj == 3){
            dw="年";
        }

        if (receiptya==19){
            return "付"+receiptfu+dw+" 押金自定義";
        }
        return "付"+receiptfu+dw+" 押"+receiptya+dw;
    }
}
